import { createFileRoute } from '@tanstack/react-router'
import { motion, AnimatePresence } from 'framer-motion'
import { useState, useEffect } from 'react'
import { StorageService, generateId } from '../services/storage'
import { SweetMomentForm } from '../components/SweetMomentForm'

export const Route = createFileRoute('/daily-sweetness')({
  component: RouteComponent,
})

interface SweetMoment {
  id: number
  date: string
  time: string
  title: string
  content: string
  mood: string
  category: 'daily' | 'surprise' | 'conversation' | 'memory'
  emoji: string
}

function RouteComponent() {
  const [selectedCategory, setSelectedCategory] = useState<string>('all')
  const [selectedMoment, setSelectedMoment] = useState<SweetMoment | null>(null)
  const [sweetMoments, setSweetMoments] = useState<SweetMoment[]>([])
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingMoment, setEditingMoment] = useState<SweetMoment | null>(null)

  // 加载数据
  useEffect(() => {
    const savedMoments = StorageService.getSweetMoments()
    if (savedMoments.length > 0) {
      setSweetMoments(savedMoments)
    } else {
      // 如果没有保存的数据，使用默认数据
      const defaultMoments: SweetMoment[] = [
    {
      id: 1,
      date: '2024-01-15',
      time: '早上 8:30',
      title: '早安吻',
      content: '今天早上醒来，她轻轻在我额头上留下一个吻，然后悄悄去厨房为我准备早餐。阳光透过窗帘洒在她身上，那一刻觉得世界都变得温柔了。',
      mood: 'sweet',
      category: 'daily',
      emoji: '😘'
    },
    {
      id: 2,
      date: '2024-01-14',
      time: '下午 3:20',
      title: '意外的奶茶',
      content: '工作到一半，她突然出现在公司楼下，手里拿着我最爱的芋泥波波奶茶。"想你了，所以来看看你"，简单的话却让我心里暖暖的。',
      mood: 'surprised',
      category: 'surprise',
      emoji: '🧋'
    },
    {
      id: 3,
      date: '2024-01-13',
      time: '晚上 9:45',
      title: '睡前的小对话',
      content: '"今天最开心的事是什么？" "遇见你啊" "那明天呢？" "继续遇见你" 每天睡前的小对话总是这么甜腻，但我永远听不腻。',
      mood: 'loving',
      category: 'conversation',
      emoji: '💭'
    },
    {
      id: 4,
      date: '2024-01-12',
      time: '傍晚 6:15',
      title: '一起做饭的时光',
      content: '今天一起做晚饭，她负责切菜我负责炒菜。虽然厨房被我们弄得一团糟，但看着她认真切菜的样子，觉得这就是最幸福的日常。',
      mood: 'cozy',
      category: 'daily',
      emoji: '👩‍🍳'
    },
    {
      id: 5,
      date: '2024-01-11',
      time: '中午 12:00',
      title: '雨天的拥抱',
      content: '突然下雨了，我们躲在公交站台下。她说冷，我就抱住了她。那一刻雨声、她的体温、还有淡淡的香水味，构成了最美好的回忆。',
      mood: 'romantic',
      category: 'memory',
      emoji: '🌧️'
    },
    {
      id: 6,
      date: '2024-01-10',
      time: '上午 10:30',
      title: '手写的便条',
      content: '在包里发现了她偷偷放的小纸条："今天也要加油哦，晚上回家有惊喜等你 💕" 简单的几个字却让我一整天都充满动力。',
      mood: 'motivated',
      category: 'surprise',
      emoji: '📝'
    }
      ]
      setSweetMoments(defaultMoments)
      StorageService.saveSweetMoments(defaultMoments)
    }
  }, [])

  // 保存数据到本地存储
  const saveMoments = (moments: SweetMoment[]) => {
    setSweetMoments(moments)
    StorageService.saveSweetMoments(moments)
  }

  // 处理表单提交
  const handleFormSubmit = (momentData: SweetMoment | Omit<SweetMoment, 'id'>) => {
    if (editingMoment) {
      // 编辑模式
      const updatedMoments = sweetMoments.map(moment => 
        moment.id === editingMoment.id ? momentData as SweetMoment : moment
      )
      saveMoments(updatedMoments)
      setEditingMoment(null)
    } else {
      // 添加模式
      const newMoment: SweetMoment = {
        ...(momentData as Omit<SweetMoment, 'id'>),
        id: parseInt(generateId(), 36)
      }
      const updatedMoments = [newMoment, ...sweetMoments]
      saveMoments(updatedMoments)
      setShowAddForm(false)
    }
  }

  // 删除甜蜜时光
  const deleteSweetMoment = (id: number) => {
    if (confirm('确定要删除这个甜蜜时光吗？')) {
      const updatedMoments = sweetMoments.filter(moment => moment.id !== id)
      saveMoments(updatedMoments)
      if (selectedMoment?.id === id) {
        setSelectedMoment(null)
      }
    }
  }

  const categories = [
    { id: 'all', label: '全部', icon: '💝' },
    { id: 'daily', label: '日常温馨', icon: '🏠' },
    { id: 'surprise', label: '意外惊喜', icon: '🎁' },
    { id: 'conversation', label: '甜蜜对话', icon: '💬' },
    { id: 'memory', label: '珍贵回忆', icon: '📸' }
  ]

  const filteredMoments = selectedCategory === 'all' 
    ? sweetMoments 
    : sweetMoments.filter(moment => moment.category === selectedCategory)

  const getMoodColor = (mood: string) => {
    const colors = {
      sweet: 'from-pink-400 to-rose-400',
      surprised: 'from-orange-400 to-amber-400',
      loving: 'from-red-400 to-pink-400',
      cozy: 'from-yellow-400 to-orange-400',
      romantic: 'from-purple-400 to-pink-400',
      motivated: 'from-green-400 to-emerald-400'
    }
    return colors[mood as keyof typeof colors] || 'from-gray-400 to-gray-500'
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-orange-50 via-pink-50 to-rose-50 py-8">
      <div className="container mx-auto px-4">
        {/* 页面标题 */}
        <motion.div 
          className="text-center mb-12"
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
        >
          <h1 className="text-5xl font-serif font-bold text-gray-800 mb-4">
            生活中的小确幸 🌻
          </h1>
          <p className="text-xl text-gray-600 max-w-2xl mx-auto">
            记录我们日常生活中那些温暖的瞬间，每一个小小的幸福都值得被珍藏
          </p>
        </motion.div>

        {/* 分类筛选 */}
        <motion.div 
          className="flex flex-wrap justify-center gap-4 mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.2 }}
        >
          {categories.map((category) => (
            <motion.button
              key={category.id}
              onClick={() => setSelectedCategory(category.id)}
              className={`px-6 py-3 rounded-full font-medium transition-all duration-300 flex items-center space-x-2 ${
                selectedCategory === category.id
                  ? 'bg-rose-500 text-white shadow-lg'
                  : 'bg-white/80 text-gray-700 hover:bg-rose-100 hover:text-rose-600'
              }`}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <span className="text-lg">{category.icon}</span>
              <span>{category.label}</span>
            </motion.button>
          ))}
        </motion.div>

        {/* 统计信息 */}
        <motion.div 
          className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6, delay: 0.4 }}
        >
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 text-center shadow-lg">
            <div className="text-3xl font-bold text-rose-600 mb-2">{sweetMoments.length}</div>
            <div className="text-gray-600">总共记录</div>
          </div>
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 text-center shadow-lg">
            <div className="text-3xl font-bold text-orange-600 mb-2">
              {sweetMoments.filter(m => m.category === 'surprise').length}
            </div>
            <div className="text-gray-600">意外惊喜</div>
          </div>
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 text-center shadow-lg">
            <div className="text-3xl font-bold text-pink-600 mb-2">7</div>
            <div className="text-gray-600">连续记录天数</div>
          </div>
        </motion.div>

        {/* 甜蜜时光列表 */}
        <motion.div 
          className="grid gap-6"
          layout
        >
          <AnimatePresence>
            {filteredMoments.map((moment, index) => (
              <motion.div
                key={moment.id}
                layout
                initial={{ opacity: 0, y: 50 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -50 }}
                transition={{ duration: 0.5, delay: index * 0.1 }}
                className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg hover:shadow-xl transition-all duration-300 cursor-pointer"
                whileHover={{ scale: 1.02, y: -5 }}
                onClick={() => setSelectedMoment(moment)}
              >
                <div className="flex items-start space-x-4">
                  <div className={`w-16 h-16 rounded-full bg-gradient-to-r ${getMoodColor(moment.mood)} flex items-center justify-center text-2xl shadow-lg`}>
                    {moment.emoji}
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-2">
                      <h3 className="text-xl font-semibold text-gray-800">{moment.title}</h3>
                      <div className="text-sm text-gray-500">
                        {moment.date} {moment.time}
                      </div>
                    </div>
                    <p className="text-gray-600 leading-relaxed line-clamp-2">
                      {moment.content}
                    </p>
                    <div className="mt-3 flex items-center justify-between">
                      <span className="px-3 py-1 bg-rose-100 text-rose-600 rounded-full text-sm">
                        {categories.find(c => c.id === moment.category)?.label}
                      </span>
                      <div className="flex space-x-2">
                        <button
                          onClick={(e) => {
                            e.stopPropagation()
                            setEditingMoment(moment)
                          }}
                          className="text-blue-500 hover:text-blue-700 text-sm"
                        >
                          ✏️ 编辑
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation()
                            deleteSweetMoment(moment.id)
                          }}
                          className="text-red-500 hover:text-red-700 text-sm"
                        >
                          🗑️ 删除
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>

        {/* 详情模态框 */}
        <AnimatePresence>
          {selectedMoment && (
            <motion.div
              className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setSelectedMoment(null)}
            >
              <motion.div
                className="bg-white rounded-3xl p-8 max-w-2xl w-full max-h-[80vh] overflow-y-auto"
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                exit={{ scale: 0.8, opacity: 0 }}
                onClick={(e) => e.stopPropagation()}
              >
                <div className="flex items-center justify-between mb-6">
                  <div className="flex items-center space-x-4">
                    <div className={`w-20 h-20 rounded-full bg-gradient-to-r ${getMoodColor(selectedMoment.mood)} flex items-center justify-center text-3xl shadow-lg`}>
                      {selectedMoment.emoji}
                    </div>
                    <div>
                      <h2 className="text-2xl font-bold text-gray-800">{selectedMoment.title}</h2>
                      <p className="text-gray-500">{selectedMoment.date} {selectedMoment.time}</p>
                    </div>
                  </div>
                  <button
                    onClick={() => setSelectedMoment(null)}
                    className="text-gray-400 hover:text-gray-600 text-2xl"
                  >
                    ✕
                  </button>
                </div>
                <div className="prose prose-lg max-w-none">
                  <p className="text-gray-700 leading-relaxed text-lg">
                    {selectedMoment.content}
                  </p>
                </div>
                <div className="mt-6 flex items-center justify-between">
                  <span className="px-4 py-2 bg-rose-100 text-rose-600 rounded-full">
                    {categories.find(c => c.id === selectedMoment.category)?.label}
                  </span>
                  <div className="flex space-x-2">
                    <motion.button
                      className="px-4 py-2 bg-pink-500 text-white rounded-full hover:bg-pink-600 transition-colors"
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                    >
                      💕 收藏
                    </motion.button>
                    <motion.button
                      className="px-4 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors"
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                    >
                      📤 分享
                    </motion.button>
                  </div>
                </div>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>

        {/* 添加新记录按钮 */}
        <motion.div 
          className="fixed bottom-8 right-8"
          initial={{ scale: 0 }}
          animate={{ scale: 1 }}
          transition={{ delay: 1, type: "spring", stiffness: 200 }}
        >
          <motion.button
            onClick={() => setShowAddForm(true)}
            className="w-16 h-16 bg-gradient-to-r from-rose-500 to-pink-500 text-white rounded-full shadow-lg flex items-center justify-center text-2xl"
            whileHover={{ scale: 1.1, rotate: 90 }}
            whileTap={{ scale: 0.9 }}
          >
            ✏️
          </motion.button>
        </motion.div>

        {/* 添加/编辑表单 */}
        <SweetMomentForm 
          isOpen={showAddForm || editingMoment !== null}
          onClose={() => {
            setShowAddForm(false)
            setEditingMoment(null)
          }}
          onSubmit={handleFormSubmit}
          initialData={editingMoment}
          categories={categories}
        />
      </div>
    </div>
  )
}
